package myky.com.doctorapp.ui

import android.Manifest
import android.content.Intent
import android.support.v4.content.ContextCompat
import android.support.v7.widget.GridLayoutManager
import android.text.TextUtils
import android.view.View
import android.widget.EditText
import android.widget.TextView
import android.widget.Toast
import com.chad.library.adapter.base.BaseQuickAdapter
import com.foamtrace.photopicker.ImageCaptureManager
import com.foamtrace.photopicker.PhotoPickerActivity
import com.foamtrace.photopicker.SelectModel
import com.foamtrace.photopicker.intent.PhotoPickerIntent
import com.gyf.barlibrary.ImmersionBar
import com.yanzhenjie.permission.Action
import com.yanzhenjie.permission.AndPermission
import com.yanzhenjie.permission.Permission
import kotlinx.android.synthetic.main.activity_feed_back.*
import kotlinx.android.synthetic.main.include_toolbar_white.*
import kotlinx.android.synthetic.main.public_common_title.*
import myky.com.doctorapp.R
import myky.com.doctorapp.adapter.FeedBackImageAdapter
import myky.com.doctorapp.base.BaseActivity
import myky.com.doctorapp.camera.MedicalTakePhotoActivity
import myky.com.doctorapp.contract.FeedBackContract
import myky.com.doctorapp.entity.FeedBackEntity
import myky.com.doctorapp.presenter.FeedBackPresenter
import myky.com.doctorapp.utils.*
import myky.com.doctorapp.wight.AddAndSubEditText
import myky.com.doctorapp.wight.SelfDialog
import java.util.*
/**
 * Description:意见反馈
 * @author xiangyao
 * Created by 2019/3/13 6:37 PM
 *
 */


/**
 * All rights Reserved, Designed By hooyue.com
 * @Title:
 * @Package
 * @Description:
 * @author: xiangyao
 * @date:   2019/3/25 11:04 AM
 * @version V1.0
 * @Copyright: xiangyao www.hooyue.com Inc. All rights reserved.
 */
class FeedBackActivity : BaseActivity<FeedBackPresenter, FeedBackEntity>(), FeedBackContract.View, BaseQuickAdapter.OnItemChildClickListener, View.OnClickListener {


    lateinit var editText: EditText

    lateinit var textView: TextView

    lateinit var imagePath: MutableList<String>

    lateinit var feedBackImageAdapter: FeedBackImageAdapter

    lateinit var selfDialog: SelfDialog


    override fun injectTarget(): View = findViewById(R.id.injectView)
    override fun initData() {
    }

    override fun initView() {
        ImmersionBar.with(this).barColorInt(ContextCompat.getColor(this, R.color.colorPrimary)).titleBar(R.id.commonTitleLayout).navigationBarEnable(false).init()

        backLayout.setOnClickListener { finish() }
        conmonTitleTextView.text = "意见反馈"
        editText = findViewById(R.id.activity_help_opinion_et)
        textView = findViewById(R.id.activity_help_opinion_tv)
        imagePath = ArrayList()
        imagePath.add("")
        AddAndSubEditText.setEditTextChangedListener(editText, textView, 200)

        activity_help_opinion_recycler.isNestedScrollingEnabled = false
        val layoutManager = GridLayoutManager(this, 3)
        activity_help_opinion_recycler.layoutManager = layoutManager
        activity_help_opinion_recycler.overScrollMode = View.OVER_SCROLL_NEVER

        feedBackImageAdapter = FeedBackImageAdapter(imagePath)


        activity_help_opinion_recycler.adapter = feedBackImageAdapter


        feedBackImageAdapter.onItemChildClickListener = this

        activity_help_opinion_btn.setOnClickListener(this)

        captureManager = ImageCaptureManager(this@FeedBackActivity)
    }


    override fun onItemChildClick(adapter: BaseQuickAdapter<*, *>?, view: View?, position: Int) {
        when (view?.id) {


            R.id.bespeak_deleteIcon -> {

                selfDialog = SelfDialog(this)
                selfDialog.setTitle("确定删除本张照片？")
                selfDialog.setYesOnclickListener("确认", SelfDialog.onYesOnclickListener {
                    selfDialog.dismiss()
                    if (imageUploadPath.contains(imagePath[position])) {
                        imageUploadPath.remove(imagePath[position])
                    }
                    imagePath.removeAt(position)
                    if (!TextUtils.isEmpty(imagePath[0])) {
                        imagePath.add(0, "")
                    }
                    feedBackImageAdapter.notifyDataSetChanged()
                })
                selfDialog.setNoOnclickListener("取消"
                ) { selfDialog.dismiss() }
                selfDialog.show()


            }
            R.id.bespeak_photo_img -> {

                val s = feedBackImageAdapter.data[position]

                if (TextUtils.isEmpty(s)) {
                    selectPhotos()
                } else {
                    ToastUtils.show("$position")
                }

            }

        }

    }

    override fun getContenView(): Int = R.layout.activity_feed_back

    override fun showDataSuccess(datas: FeedBackEntity?) {

        val type = datas?.type

        if (type == 113) {
            uploadFeedContent()
        } else if (type == 3) {
            if (!isFinishing) {
                selfDialog = SelfDialog(this@FeedBackActivity)
                selfDialog.setTitle("提交成功")
                selfDialog.setMessage("感谢您的关注和支持，我们会认真处理您的反馈，尽快修复和完善")
                selfDialog.setYesOnclickListener("确定", SelfDialog.onYesOnclickListener {
                    selfDialog.dismiss()
                    val intent = Intent(this@FeedBackActivity, MainActivity::class.java)
                    intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP)
                    startActivity(intent)
                })
                selfDialog.show()
            }
        } else {
            if (!isFinishing) {
                DialogChoice.setDialog(this@FeedBackActivity, "提交失败", "服务异常,请稍候再试", 0)
            }
        }

    }

    override fun reloadActivity() {
    }

     var captureManager: ImageCaptureManager? =null
    private val imageUploadPath = ArrayList<String>()
    private val REQUEST_CAMERA_CODE = 22

    private fun selectPhotos() {
        DialogChoice.setDialog_ChoosePhoto(1, this, 9) { onclick ->
            when (onclick) {
                Constants.TAKE_TYPE -> try {
                    if (captureManager == null) {
                        captureManager = ImageCaptureManager(this@FeedBackActivity)
                    }

                    AndPermission.with(this)
                            .permission(Manifest.permission.CAMERA)
                            .rationale { context, data, executor ->

                                executor.execute()

                            }
                            .onGranted {

                                val intent = Intent(this@FeedBackActivity, MedicalTakePhotoActivity::class.java)
                                intent.putExtra("TypeName", "")
                                startActivityForResult(intent, ImageCaptureManager.REQUEST_TAKE_PHOTO)

                            }

                            .onDenied { data: MutableList<String>? ->
                                if(AndPermission.hasAlwaysDeniedPermission(this,data)){
                                    AndPermission.permissionSetting(this@FeedBackActivity).execute();
                                    return@onDenied
                                }

                            }
                            .start()



                } catch (e: Exception) {
                    Toast.makeText(this@FeedBackActivity, com.foamtrace.photopicker.R.string.msg_no_camera, Toast.LENGTH_SHORT).show()
                    e.printStackTrace()
                }

                Constants.PHOTO_TYPE -> {

                   AndPermission.with(this)
                           .permission(Manifest.permission.READ_EXTERNAL_STORAGE)
                           .rationale { context, data, executor ->

                               executor.execute()
                           }
                           .onGranted {

                               val intent = PhotoPickerIntent(this@FeedBackActivity)
                               intent.setSelectModel(SelectModel.MULTI)
                               intent.setShowCarema(false) // 是否显示拍照
                               intent.setMaxTotal(9) // 最多选择照片数量，默认为9
                               intent.setSelectedPaths(imageUploadPath) // 已选中的照片地址， 用于回显选中状态
                               startActivityForResult(intent, REQUEST_CAMERA_CODE)

                           }.onDenied{ data: MutableList<String>? ->


                               if(AndPermission.hasAlwaysDeniedPermission(this,data)){
                                   AndPermission.permissionSetting(this@FeedBackActivity).execute();
                                   return@onDenied
                               }
                           }
                           .start()


                }
            }
        }
    }

    override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {
        super.onActivityResult(requestCode, resultCode, data)
        if (data != null && resultCode == RESULT_OK) {
            when (requestCode) {
                // 选择照片
                REQUEST_CAMERA_CODE -> {
                    imagePath.clear()
                    imageUploadPath.clear()
                    if (data.getStringArrayListExtra(PhotoPickerActivity.EXTRA_RESULT) != null) {
                        imagePath.addAll(data.getStringArrayListExtra(PhotoPickerActivity.EXTRA_RESULT))
                        if (imagePath.size < 9) {
                            imagePath.add(0, "")
                        }
                        imageUploadPath.addAll(data.getStringArrayListExtra(PhotoPickerActivity.EXTRA_RESULT))
                    }
                    if (imagePath.size > 9) {
                        imagePath.removeAt(0)
                    }
                    feedBackImageAdapter.notifyDataSetChanged()
                }

                // 调用相机拍照
                ImageCaptureManager.REQUEST_TAKE_PHOTO -> {
                    val path = data.getStringExtra("path")
                    captureManager?.galleryAddPic(path)
                    imagePath.add(path)
                    imageUploadPath.add(path)
                    if (imagePath.size > 9) {
                        imagePath.removeAt(0)
                    }
                    feedBackImageAdapter.notifyDataSetChanged()
                }
            }
        }
    }

    override fun onClick(p0: View?) {

        when (p0?.id) {

            R.id.activity_help_opinion_btn -> {

                uploadFeedContent()
            }

        }
    }

    private fun uploadFeedContent() {
        val mobile = activity_help_opinion_tel.getText().toString().trim { it <= ' ' }
        var isMobile = false
        if (mobile == "") {
            isMobile = true//可以不填联系人电话
        } else {
            isMobile = CheckText.isMobileNumber(mobile)
        }
        if (isMobile) {
            if (TextUtils.isEmpty(editText.text.toString().trim { it <= ' ' })) {
                ToastUtils.show("请输入反馈意见")
                return
            }
            if (imageUploadPath.size == 0) {


                val userID = ShareUtil.getInt(Constants.USERID)

                val userName = ShareUtil.getString(Constants.USERNAME)

                val conten = activity_help_opinion_et.text.toString()

                mPresenter.upFeedContent(userID.toString(), userName, SystemUtil.getSystemModel(), SystemUtil.getSystemVersion(), SystemUtil.getSystemModel(), conten, mobile, null)

            } else {
                selfDialog = SelfDialog(this@FeedBackActivity)

                selfDialog.creatProgressDialog(this@FeedBackActivity, "正在上传，请稍后...")
            }
        } else {
            ToastUtils.show("请填写正确的手机号码")
        }
    }

    override fun getPresenter(): FeedBackPresenter {
        return FeedBackPresenter()
    }

}
